/**
 * 2点到5点夜间行车分析
 */
var iFrameName = this.name;
var cityCenter=localStorage.getItem('cityMapCenter').split(',');
var nightDriving2To5 = {
	init: function(){
		var me = this;
		me.time=[];
		me.speed=[];
    	me.startTime = null;
    	me.endTime = null;
		me.queryChose="ent";
		me.enterpriseList = null;
		me.addressPath = null;
		me.initQueryTime();
		me.barChart = me.initBarChart();
		me.pieChart = me.initPieChart();
		me.initEvent();
		me.initEcharts();
		me.initEnterpriseList();
		me.queryBarChartData();
		me.initVehicleList();
		me.initDetailsTable();
	},
	initEvent: function(){
		var me = this;
		//业户和车牌号选择按键
		$("#choseSelect").on('change',function(){
			var chose = $("#choseSelect").val();
			if (chose == "vehicle") {
				me.queryChose="veh";
				$("#selectEnterprise").hide();	
				$("#selectVehicle").show();
			}else if (chose == "enterprise") {
				me.queryChose="ent";
				$("#selectVehicle").hide();
				$("#selectEnterprise").show();
			}
		});
		$("#choseSelect").select2();
		$("#queryBtn").click(function(){
			alert("123");
			me.queryBarChartData();
			 $("#resultTable").flexOptions({
	            	url: appCtx +"/report/nightDriving2To5/getResultTableByEnt.html?time="+ new Date().getTime(),
	            	params: me.getparams(),
	                newp: 1
	            }).flexReload();
    	});
		$("#exportExcel").click(function(){
			me.exportNightDriving();
		});
		//确定按钮事件
 		$("#confirmOK").click(function() {
            $('#confirmModal').modal('hide');
	    	me.onCallBack(mFrameName,mDialogCallback);
        });
 		 		
 		$("#btnSaveOK").click(function() {
 			eval("("+mDialogOkCall+")");
            $('#confirmModal').modal('hide');
            return false;
        });

 		$("#confirmExport").click(function() {
           // $('#exportModal').modal('hide');
	    	me.onCallBack(mFrameName,mDialogCallback);
        });
 		
 		/* 上一步、下一步 模态框 保存按钮 事件 */
 		$("#btnSave").click(function() {
 			eval("("+mDialogSaveCall+")");
            $('#confirmModal').modal('hide');
            return false;
        });
		$('.detail-report').on('click',"img[name='trackPlayBtn']",function(){
			var vehicle_no_color = $(this).attr('vehicle_no_color');
			var vehicle_no = $(this).attr('vehicle_no');
   			var vehicle_color = $(this).attr('vehicle_color');
     		var start_time = $(this).attr('startTime');
     		var end_time = $(this).attr('endTime');
     		var address2 = $(this).attr('address2');
     		var address5 = $(this).attr('address5');
     		var base64 = new Base64();
      		$.ajax({
        		type : 'post',
        		async : true,
        		url : appCtx+'gis/playback/queryTrackList.html?vehicle_no_color='+base64.encode(vehicle_no_color)+"&start_time="+start_time+"&end_time="+end_time,
        		dataType : "JSON",
        		data:{},
        		success : function(rdata) {	
        			if(rdata.length>0){
        				var data = rdata.rows;
        				for(var i=0;i<data.length;i++){
        					var retime = me.getFromatTime(data[i].gpsTime);
        					me.time.push(retime);
	        				me.speed.push(data[i].gpsSpeed);
        				}
        				me.myChart.setOption({
                            xAxis: {
                                data: me.time
                            },
                            series: [{
                                name:'速度',
                                data: me.speed
                            }]
                        });

        				var lnglatArr = new Array();
        				for(var i=0;i<data.length;i++){
        					var lng = data[i].longitudeD;
        					var lat = data[i].latitudeD;
        					var lnglat = new Array();
            				lnglat.push(lng);
            				lnglat.push(lat);
            				lnglatArr.push(lnglat);
        				}
        				var carPic = appCtx + "resources/images/mapTool/car1.png";//TODO 无法获取车辆类型，暂时先取0
        				me.initMapNoMarker(carPic,lnglatArr,vehicle_no,vehicle_color,address2,address5);
        			
        			}else{
        				me.myChart.setOption({
                            xAxis: {
                                data: [""]
                            },
                            series: [{
                                name:'速度',
                                data: [0]
                            }]
                        });
        				var map = new AMap.Map("mymap", {
        			        resizeEnable: true,
        			        center: cityCenter,
        			        zoom: 11
        			    });
        				global.ajaxLoading.pop("无轨迹数据", false, 2000);
        				/*var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)}); 
        	    		me.infoWindow = infoWindow;
        	    		marker = new AMap.Marker({
        	    		    map: map,
        	    		    position:cityCenter,
        	    		    icon: "",
        	    		    offset: new AMap.Pixel(-15, -10),
        	    		    autoRotation: true
        	    		});
        	    		marker.content = '无轨迹数据';
        	    		infoWindow.setContent(marker.content);
        	    		infoWindow.open(map, marker.getPosition());*/
        			}
        		}
        	});
		});
	},
	initMapNoMarker: function(carPic,lineArr,vehicle_no,vehicle_color,address2,address5){
		var map = new AMap.Map("mymap", {
	        resizeEnable: true,
	        center: lineArr[0],
	        zoom: 14
	    });
	    startMarker = new AMap.Marker({
	        map: map,
	        position: lineArr[0],
	        icon: global.url.domain + "gps-web/resources/images/mapTool/p_start.png",
	        offset: new AMap.Pixel(-15, -30)
	    });
	    var content2 ='车牌：'+vehicle_no+'</br>车牌色：'+vehicle_color+ '</br>定位位置: '+address2;
	    var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)});
	    infoWindow.setContent(content2);
	    infoWindow.open(map, startMarker.getPosition());
	    endMarker = new AMap.Marker({
	        map: map,
	        position: lineArr[lineArr.length-1],
	        icon: global.url.domain + "gps-web/resources/images/mapTool/p_end.png",
	        offset: new AMap.Pixel(-15, -30)
	    });
		 marker = new AMap.Marker({
		        map: map,
		        position:  lineArr[0],
		        icon: carPic,
		        offset: new AMap.Pixel(-26, -13),
		        autoRotation: true
		    });
	    // 绘制轨迹
	    var polyline = new AMap.Polyline({
	        map: map,
	        path: lineArr,
	        strokeColor: "#00A",  //线颜色
	        // strokeOpacity: 1,     //线透明度
	        strokeWeight: 3,      //线宽
	        // strokeStyle: "solid"  //线样式
	    });
	    var passedPolyline = new AMap.Polyline({
	        map: map,
	        // path: lineArr,
	        strokeColor: "#F00",  //线颜色
	        // strokeOpacity: 1,     //线透明度
	        strokeWeight: 3,      //线宽
	        // strokeStyle: "solid"  //线样式
	    });
	    marker.on('moving',function(e){
	        passedPolyline.setPath(e.passedPath);
	    })
	    map.setFitView();
	    marker.moveAlong(lineArr, 20000);
	},
	//初始化时间选框
    initQueryTime:function(){
        var todayDate = new Date();
        var beforeDate = new Date(todayDate-86400000*1); //前一天
	    var yyyy = beforeDate.getFullYear(), mm = (beforeDate.getMonth() + 1).toString(), dd = beforeDate.getDate().toString();
	    if (mm.length == 1) {
	        mm = '0' + mm;
	    }
	    if (dd.length == 1) {
	        dd = '0' + dd;
	    }
	    $("#inputStartDate").val(yyyy + '-' + mm + '-' + dd);
        $("#inputEndDate").val(yyyy + '-' + mm + '-' + dd);
      },
      initEcharts : function(){
  		var me=this;
  		me.myChart = echarts.init(document.getElementById('speedCharts'));
      	var option = {
      		    xAxis: {
      		    	type : 'category',
      	            boundaryGap : false,
      		        data:me.time 
      		    },
      		    grid:{
      		    	x:30,
      		    	y:30,
      		    	x2:5,
      		    	y2:5
      		    	
      		    },
      		    
      		    calculable : true,
      		    tooltip: {
      		        trigger: 'axis',
      		        formatter: function (params) {
      		            params = params[0];
      		            return "时间:"+params.name+"<br/>"+"速度:"+params.value;
      		        },
      		        axisPointer: {
      		            animation: false
      		        }
      		    },
      		    yAxis: {
      		        name : '速度(km/h)',
      			    type : 'value',
      			    max : 150,
      			    data : [30,60,90,120,150]
      		    },
      		    series: [
      		        {
      		            name:'速度',
      		            type:'line',
      		            smooth:true,
      		            stack: 'a',
      		            data: [0]
      		        }
      		    ]
      		};
      	me.myChart.setOption(option);
      },
	/*车辆图标*/
    getVehicleStatusPicUrl : function(status){
        var carStatus = ['car','car','carYellow','red','gray'];
        var picUrl = appCtx + "resources/images/mapTool/";
        try{
            picUrl += (carStatus[status])+"1.png";
            return picUrl;
        }catch(ex){
            console.log(ex);
            return picUrl  = appCtx + "resources/images/mapTool/car1.png";  //出错的话 默认车辆图标
        }
    },
    // 获取查询条件
    getparams: function () {
		var me = this;
		var vehicle_no=$.trim($("#selectVehicleSel").val());
		var enterprise_name=$.trim($("#selectEnterpriseSel").val());
        var startTime = $("#inputStartDate").val()+" 00:00:00";
        var endTime = $("#inputEndDate").val()+" 23:59:59";
        var queryChose = me.queryChose;
        var end_str = (endTime).replace(/-/g,"/");//一般得到的时间的格式都是：yyyy-MM-dd hh24:mi:ss，所以我就用了这个做例子，是/的格式，就不用replace了。  
    	var end_date = new Date(end_str).getTime();//将字符串转化为时间  
    	//开始时间  
    	var sta_str = (startTime).replace(/-/g,"/");  
    	var sta_date = new Date(sta_str).getTime(); 
    	me.startTime = sta_date;
    	me.endTime = end_date;
        var params = [{
        	name: 'enterprise_name',
            value: enterprise_name
        }, {
            name: 'vehicle_no',
            value: vehicle_no
        }, {
            name: 'queryChose',
            value: queryChose
        }, {        	
            name: 'startTime',
            value: sta_date
        }, {
            name: 'endTime',
            value: end_date
        }];
        return params;
    },
	//初始化柱状图
	initBarChart: function(){
		var me = this;
		//计算显示的柱子数
		var percent = 100;

		option = {
			title:{text:'',x:'center',textStyle:{fontSize:12,fontWeight:400} },
		    color: ['#3398DB'],
		    tooltip : {
		        trigger: 'axis',
		        show: true,
		        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
		        	show: true,
		            type : 'line'        // 默认为直线，可选为：'line' | 'shadow'
		        },
		    },
		    grid: {
		    	left: '40px',
		        top:'40px',
		        right: '10px',
		        bottom:"15%",
//		        containLabel: true
		    },
		    
		    xAxis : [
		        {
		            type : 'category',
		            data : [],
		            name: '',
		            axisTick: {
		                alignWithLabel: true
		            },
		            axisLabel:{
		            	textStyle: {
                            fontSize: 10
                        }
		            }
		        }
		    ],
		    yAxis : [
		        {
		            type : 'value',
		            show: true,    //显示纵轴false-不显示，true-显示
		            minInterval:1,
                    min:0,
                    axisLabel: {
                        formatter: function (value, index) {
                        	if (value >= 1 || value == 0) {
                            	if (value%1 === 0) {
                            		return value;
                            	}
                            }
                        }
                    },

		            name: '车辆数/辆'
		        }
		    ],
		    series : [
		        {
		            name:'夜间行驶车辆数',
		            type:'bar',
		            barMaxWidth : '60px',
		            data:[]
		        }
		    ],
		    dataZoom: [{
		        type: 'inside',
		        start: 0,
		        end: percent
		    }, {
		        start: 0,
		        end: percent,
		        fillerColor:'#A3E1A3',
		        handleColor:'#83A7D1',
		        showDetail:false
		    }]
		};
            var myChart = echarts.init(document.getElementById('barChart'));
            myChart.setOption(option);
            window.onresize = myChart.resize;
            myChart.on('click', function(param){
            	var end_date = me.endTime;
            	var sta_date = me.startTime;
            	var enterpriseList = me.enterpriseList;
            	var enterprise_name = enterpriseList[param.dataIndex];
            	 $("#resultTable").flexOptions({
 	            	url: appCtx +"/report/nightDriving2To5/getResultTableByEnt.html?time="+ new Date().getTime(),
 	            	params: [{name:"endTime",value:end_date},{name:"startTime",value:sta_date},{name:"queryChose",value:"ent"},
 	            		{name:"vehicle_no",value:''},{name:"enterprise_name",value:enterprise_name}],
 	                newp: 1
 	            }).flexReload();
            });
            return {
            	refash : function(option){
                    myChart.setOption(option);
            	},
            	option : option,
            	barChartDom : myChart
            };        
	},
	initPieChart: function(){
		option = {
				title:{text:'',x:'center',textStyle:{fontSize:12,fontWeight:400} },
			    tooltip : {
			        trigger: 'item',
			        formatter: "{b}<br/>   {c}辆    :  ({d}%)"
			    },
			    legend: {
			        orient: 'vertical',
			        left: 'left',
			        data: [],
			        show: false
			    },
			    color:['#2a5ab1'],
			    series : [
			        {
			            name: '',
			            type: 'pie',
			            center: ['50%', '50%'],
			            radius : ['55%', '75%'],
			            itemStyle : {
			                normal : {
			                    label : {
			                        show : false,
			                        position : 'center'
			                    },
			                    labelLine : {
			                        show : false
			                    }
			                },
			                emphasis : {
			                    label : {
			                        show : true,
			                        textStyle : {
			                            fontSize : '20',
			                            fontWeight : 'bold'
			                        }
			                    },
			                    labelLine : {
			                        show : false
			                    }
			                }
			            },
			            data:[]
			           /* itemStyle: {
			                emphasis: {
			                    shadowBlur: 10,
			                    shadowOffsetX: 0,
			                    shadowColor: 'rgba(0, 0, 0, 0.5)'
			                },
			               normal:{ 
				                  label:{ 
				                    show: true, 
				                    formatter: "{c} 辆 ({d}%)"
				                  }, 
				                  labelLine :{show:true} 
				            }
			            }*/
			        }
			    ],
			    color: [
			    	'#8d98b3','#2ec7c9','#97b552','#95706d','#dc69aa',
			    	'#e5cf0d','#b6a2de','#5ab1ef','#ffb980','#d87a80',
			        '#07a2a4','#9a7fd1','#588dd5','#f5994e','#c05050',
			        '#59678c','#c9ab00','#7eb00a','#6f5553','#c14089'
			    ]			
		};
		
		 var myChart = echarts.init(document.getElementById('pieChart'));
         myChart.setOption(option);
         window.onresize = myChart.resize;
         return {
         	refash : function(option){
                 myChart.setOption(option);
         	},
         	option : option,
         	pieChartDom : myChart
         };
	},
	//加载车辆列表
	initVehicleList:function(){
		$('#selectVehicleSel').select2({
    		theme: "default",
 	        allowClear: true,
 	        placeholder: "全部车辆",
 	        ajax:{
 	            url:appCtx + "/report/nightDriving2To5/queryVehicleListByRole.html?time="+new Date().getTime(),
 	            dataType:"json",
 	            delay:250,
 	           async : true,
 	            data:function(params){
 	                return {
 	                    name: params.term,
 	                    page: params.page || 1
 	                };
 	            },
 	            cache:true,
 	            processResults: function (res, params) {
 			    	if(res){
 			    		var options = [];
 			    		var option = {"id":" ", "text":"全部车辆"};
 			    		options.push(option);
 	    				$.each(res,function(index,obj) {
 	    					var option = {"id":obj.vehicle_no, "text":obj.vehicle_no};
     	                    options.push(option);
 	    				});
     	                return {
     	                	results: options,
     	                    pagination: {
     	                        more:false
     	                    }
     	                };
 			    	}
 	            },
 	            escapeMarkup: function (markup) { return markup; },
 	            minimumInputLength: 1
 	        }
    	})
		/*var me = this;
		$.ajax({
			type : 'post',
			url : appCtx + "/report/nightDriving2To5/queryVehicleListByRole.html?time="+new Date().getTime(),
			cache : true,
			dataType : "JSON",
			success : function(data) {
				var selectStr="<option value=''>全部车辆</option>";
				$.each(data,function(index,ve){
					selectStr+="<option value='"+ve.vehicle_no+"'>"+ve.vehicle_no+"</option>";
				});
				$('#selectVehicleSel').html(selectStr);		
				$("#selectVehicleSel").select2();
			}
		});*/
	},
	//加载业户列表
	initEnterpriseList: function(){
		$('#selectEnterpriseSel').select2({
    		theme: "default",
 	        allowClear: true,
 	        placeholder: "全部业户",
 	        ajax:{
 	            url:appCtx + "/system/common/queryEnterprise.html?time="+new Date().getTime(),
 	            dataType:"json",
 	            delay:250,
 	           async : true,
 	            data:function(params){
 	                return {
 	                    name: params.term,
 	                    page: params.page || 1
 	                };
 	            },
 	            cache:true,
 	            processResults: function (res, params) {
 			    	if(res){
 			    		var options = [];
 			    		var option = {"id":" ", "text":"全部业户"};
 			    		options.push(option);
 	    				$.each(res,function(index,obj) {
 	    					var option = {"id":obj.text, "text":obj.text};
     	                    options.push(option);
 	    				});
     	                return {
     	                	results: options,
     	                    pagination: {
     	                        more:false
     	                    }
     	                };
 			    	}
 	            },
 	            escapeMarkup: function (markup) { return markup; },
 	            minimumInputLength: 1
 	        }
    	})
		/*var me = this;
		$.ajax({
			type : 'post',
			url : appCtx + "/system/common/queryEnterprise.html?time="+new Date().getTime(),
			cache : true,
			dataType : "JSON",
			success : function(data) {
					var selectStry="<option value=''>全部业户</option>";
					$.each(data,function(index,ent){
						selectStry+="<option value='"+ent.text+"'>"+ent.text+"</option>";
					});
					$('#selectEnterpriseSel').html(selectStry);		
					$("#selectEnterpriseSel").select2();
					$("#selectEnterpriseSel").change(function(){
					});
				}
		});*/
	
	},
	
	queryBarChartData: function(){
		var me = this;
		$.ajax({
			type : 'post',
			async : true,
			url : appCtx+"/report/nightDriving2To5/getBarChartData.html?time="+new Date().getTime(),
			data:nightDriving2To5.getparams(),
			dataType : "JSON",
			success : function(data) {
				$("#noData").remove();
					var option_bar = me.barChart.option;
					option_bar.xAxis[0].data =data.xAxisData; //['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
					option_bar.series[0].data =data.series;// [10, 52, 200, 334, 390, 330, 220];
					me.barChart.refash(option_bar);
					var startTime = data.start_time;
					var endTime = data.end_time;
					me.startTime = startTime;
			    	me.endTime = endTime;				
					me.enterpriseList=data.xAxisData;
					me.addressPath = data.address_Path;
					var enterprise_name = data.xAxisData[0];
					//向饼状图中添加数据，并刷新
					var option_pie = me.pieChart.option;
					//option_pie.legend.data = data.xAxisData;
					if(data && data.series && data.series[0] != 0){
						var arr =  new Array();
						for (var i = 0; i < data.series.length; i++) {
							var map = {};
							map["value"]=data.series[i];
							map["name"]=data.xAxisData[i];
							arr.push(map);
						}
						option_pie.series[0].data = arr;
						me.pieChart.refash(option_pie);
					}else{
//						$("#pieChart").hide();
						global.noData("#pieChart")
					}
			}
		});
	},
	/**
	 * 查询分页显示
	 *@Description: 用户单击条形图的某一条,获取条形图的详细列表
	 */
    initDetailsTable: function(){
    	var me = this;
		$("#resultTable").flexigrid({
			url : appCtx + "/report/nightDriving2To5/getResultTableByEnt.html?time="+ new Date().getTime(),
			dataType : 'json',
			colModel : nightDriving2To5.getColumn(),
			params: me.getparams(),
            contentType: "application/json; charset=utf-8",
			resizable : false,
			minheight: '80px', //列的最小高度
			nowrap: true, //是否不换行
			sortname : "vehicle_no",// 第一次加载数据时排序列
			sortorder : "desc",// 第一次加载数据时排序类型
			usepager : true,// 是否分页，默认为true。
			showToggleBtn : false,
			showTableToggleBtn : true,// 是否显示收起/打开按钮,默认不显示。
			useRp : true,// 是否可以动态设置每页显示的结果数，默认为false。
			rp : 5,// 每页记录数，默认为10
			rpOptions: [5,10, 20,50, 100], // 每页结果数
			checkbox : false,// 是否要多选框,默认为false。
			rowId : 'vehicleId',// 多选框绑定行的id,只有checkbox : true时才有效。
			singleSelect : true,
			widthType:"%",
			width : $('.detail-report').width(),
			height : 310,
			titDisplay: false,
            onSuccess: function (data) {
            	if (data) {
            		$.each(data.rows,function(index,vehicle){
            			var address_Path = nightDriving2To5.addressPath;
            			if (typeof(vehicle.coordinates_two.coordinates) != "undefined" && typeof(vehicle.coordinates_five.coordinates) != "undefined") {
                			var longitude2 = vehicle.coordinates_two.coordinates[0];
             			    var latitude2 = vehicle.coordinates_two.coordinates[1];
     	        		    var longitude5 = vehicle.coordinates_five.coordinates[0];
    	       			    var latitude5 = vehicle.coordinates_five.coordinates[1];
    	       			    var analyse_date = vehicle.analyse_date;
    		       			var date = new Date(analyse_date);
    		     		    var y = date.getFullYear();    
    		     		    var m = date.getMonth() + 1;    
    		     		    m = m < 10 ? ('0' + m) : m;    
    		     		    var d = date.getDate();    
    		     		    d = d < 10 ? ('0' + d) : d; 
    		     	    	var day = y+"-"+m+"-"+d;
//    		     	    	var startStr = "2017-09-10"+" 2:00:00"
//    		     	    	var endStr = "2017-09-05"+" 5:00:00"
    		     	    	var startStr = day+" 2:00:00"
    		     	    	var endStr = day+" 5:00:00"
    		     	    	var startTime = new Date(startStr);
    		     	    	var endTime = new Date(endStr);
    		     	    	var vehicle_no_color = vehicle.vehicle_no+"_"+vehicle.vehicle_color;
                			var backId = "#"+vehicle.index+"back";
                			$(backId).attr('vehicle_no', vehicle.vehicle_no);
                			$(backId).attr('vehicle_color',vehicle.vehicle_color_name);
                			$(backId).attr('vehicle_no_color',vehicle_no_color);
                			$(backId).attr('startTime',startStr);
                			$(backId).attr('endTime',endStr);
                		   //获取定位地址
            			   var id2 = "#"+vehicle.index+"2";
            		 	   $.ajax({
            		 	         url : address_Path + "?location="+longitude2+","+latitude2,
            		 	         dataType : 'jsonp',
            		 	         async:true, 
            		 	         success : function(data){
        		 	                if(data.info != "OK") return;
        		 	                var address = data.regeocodes[0].formatted_address;
        		 	                if(address == "") return;
        		 	                $(id2).html(address);
        		 	                $(id2).attr('title',address);
        		 	                $(backId).attr('address2',address);
            		 	          }
            		 	    });
            		 	   var id5 = "#"+vehicle.index+"5";  
    	       		 	   $.ajax({
    	       		 	         url : address_Path + "?location="+longitude5+","+latitude5,
    	       		 	         dataType : 'jsonp',
    	       		 	         async:true, 
    	       		 	         success : function(data){
           		 	                if(data.info != "OK") return;
           		 	                var address = data.regeocodes[0].formatted_address;
           		 	                if(address == "") return;
           		 	                $(id5).html(address);
	           		 	            $(id5).attr('title',address);
	           		 	            $(backId).attr('address5',address);
    	       		 	         }
    	       		 	    });
						}
            			
    				});
				}
            },
            
     	});
    },
	  getFromatTime : function (msg){
	  	  if (null != msg && undefined != msg ) {
		  		var date = new Date(parseInt(msg)); 
	  		    var y = date.getFullYear();    
	  		    var m = date.getMonth() + 1;    
	  		    m = m < 10 ? ('0' + m) : m;    
	  		    var d = date.getDate();    
	  		    d = d < 10 ? ('0' + d) : d;    
	  		    var h = date.getHours();  
	  		    h = h < 10 ? ('0' + h) : h;  
	  		    var minute = date.getMinutes();  
	  		    var second = date.getSeconds();  
	  		    minute = minute < 10 ? ('0' + minute) : minute;    
	  		    second = second < 10 ? ('0' + second) : second;   
	  		  var outTime = y + '-' + m + '-' + d+'  '+h+':'+minute+':'+second;
		  	  	}
		  	  return outTime;
	    },
    getColumn:function(){
    	return [{
            display : '序号',
            name : 'index',
            width : 6,
            sortable : true,
            showTitle:true,
            align : 'left'
        },{
            display : '车牌号',
            name : 'vehicle_no',
            width : 12,
            sortable : false,
            showTitle:true,
            align : 'left',
        },{
            display : '颜色',
            name : 'vehicle_color_name',
            width : 7,
            sortable : false,
            align : 'left',
        },{
            display : '所属业户',
            name : 'enterprise_name',
            width : 15,
            sortable : false,
            showTitle:true,
            align : 'left',
        },{
            display : '2点位置',
            name : 'coordinates_two',
            width : 22,
            sortable : false,
            align : 'left',
            paramcolnames:['index'],
            handlefunction:function(index){
            	var handleStr = "<span style='height:30px;width:140px;' id='"+index+"2'></span>";	
            	return handleStr;
            }
        },{
            display : '5点位置',
            name : 'coordinates_five',
            width : 22,
            sortable : false,
            align : 'left',
            paramcolnames:['index'],
            handlefunction:function(index){
            	var handleStr = "<span style='height:30px;width:140px;' id='"+index+"5'></span>";		
        		return handleStr;
            }
        },{
            display : '行驶里程',
            name : 'mileage_2_5',
            width : 10,
            sortable : false,
            showTitle:true,
            align : 'left',
        },{
        	display : '操作',
            name : 'Handler',
            width : 10,
            sortable : false,
            align : 'left',
            paramcolnames:['index'],
            handlefunction:function(index){
            	//<span>轨迹回放</span>
            	var handleStr =  "<a href='JavaScript::' title='轨迹回放'>" +
        				"<img name='trackPlayBtn' id='" +index+"back' src='"+appCtx+"resources/images/track.png' ></a>";		
        		return handleStr;
            }
        }]
    },
    getExColumn :function(){
    	
    	return [{
            display : '序号',
            name : 'index',
            width : 80,
            sortable : true,
            align : 'left'
        },{
            display : '车牌号',
            name : 'vehicle_no',
            width : 100,
            sortable : false,
            align : 'left',
        },{
            display : '颜色',
            name : 'vehicle_color_name',
            width : 80,
            sortable : false,
            align : 'left',
        },{
            display : '所属业户',
            name : 'enterprise_name',
            width : 300,
            sortable : false,
            align : 'left',
        },{
            display : '2点位置',
            name : 'coordinates_two',
            width : 300,
            sortable : false,
            align : 'left',
        },{
            display : '5点位置',
            name : 'coordinates_five',
            width : 300,
            sortable : false,
            align : 'left',
        },{
            display : '行驶里程(公里)',
            name : 'mileage_2_5',
            width : 100,
            sortable : false,
            align : 'left',
        }]
    },
    exportComfirm:function(){
		var me = this;
		var options = $("#resultTable").getOptions();
		//总记录数
		var total = options.total;
		//开始页数
		var StartPage=window.parent.$("#StartPageIndex").val();
		//结束页数
		var EndPage=window.parent.$("#EndPageIndex").val();
		var validate=true;
		var msg="";
		if(!StartPage || StartPage==0){
			msg+="起始页不能为空或者0";
			validate=false;
		}
		if(!EndPage || EndPage==0){
			msg+="结束页不能为空或者0";
			validate=false;
		}
		
		if(StartPage && EndPage &&EndPage<StartPage){
			msg+="结束页要大于起始页";
			validate=false;
		}
		if(!validate){
			me.ajaxLoading(msg,false,2000);
			return;
		}
		$('#exportModal').modal('hide');
		me.ajaxLoading("正在导出,请稍后.....",true,2000);
		//每页大小
		var pagesize = options.rp;
		
		//获取导出的参数
		var exportParams = options.exportParams;
		if((EndPage - StartPage + 1) * pagesize > 60000&&total>60000)
		{
			global.ajaxLoading.pop("最多只能导出60000条数据", true, 2000);
			return
		}
		
        var column = me.getExColumn();
        var exportColumns = new Array();
        for(var i=0;i<column.length;i++){
        	if(column[i].hide!=true){
        		exportColumns.push(column[i]);
        	}
        }
		var header1 = JSON.stringify(exportColumns);
		
		//图片
		 var imageUrl = me.barChart.barChartDom.getDataURL({
				type: 'png',
			    pixelRatio: 1
		}); 
		 var imageUrl2 = me.pieChart.pieChartDom.getDataURL({
				type: 'png',
			    pixelRatio: 1
		}); 
		var imgsrcList=new Array();
		imgsrcList.push(imageUrl);
		imgsrcList.push(imageUrl2);
		var imgsrc= $.toJSON(imgsrcList);
		//表头
		var colModelList=new Array();
		colModelList.push(header1);
		var colModel= $.toJSON(colModelList);	
		var vehicle_no=$.trim($("#selectVehicleSel").val());
		var enterprise_name=$.trim($("#selectEnterpriseSel").val());
        var startTime = $("#inputStartDate").val()+" 00:00:00";
        var endTime = $("#inputEndDate").val()+" 23:59:59";
        var queryChose = me.queryChose;
        var end_str = (endTime).replace(/-/g,"/");//一般得到的时间的格式都是：yyyy-MM-dd hh24:mi:ss，所以我就用了这个做例子，是/的格式，就不用replace了。  
    	var end_date = new Date(end_str).getTime();//将字符串转化为时间  
    	//开始时间  
    	var sta_str = (startTime).replace(/-/g,"/");  
    	var sta_date = new Date(sta_str).getTime(); 
    	me.startTime = sta_date;
    	me.endTime = end_date;
		var paramsGrid =  {
				colModel:colModel,
				title:"2点至5点夜间行车表",
				enterprise_name:enterprise_name,
				vehicle_no:vehicle_no,
				queryChose:queryChose,
				start_time:sta_date,
				end_time:end_date,
				imgsrc:imgsrc,
				StartPage:StartPage,
				EndPage:EndPage,
				pagesize:pagesize
		};
		
		post(appCtx + "/report/nightDriving2To5/exportResultTable.html",paramsGrid);
	},
	/**
	 * 导出业户信息
	 */
	exportNightDriving: function(){
		var me=this;
		var options = $("#resultTable").getOptions();
		var total = options.total;
		if(total==0){
			me.ajaxLoading("无导出数据",false,2000);
			return;
		}
		var pages = options.pages;
		//设置默认的开始结束页
		$("#StartPageIndex").val(1);
		$("#EndPageIndex").val(pages);
		me.doExportModal("导出2点至5点夜间行车信息",iFrameName,"nightDriving2To5.exportComfirm()");   
	},
	ajaxLoading:function (msg,flag,time){
		global.ajaxLoading.pop(msg,flag,time);
	},

	closeDataDialog:function (){
		 $("#dataModal").modal("hide");
	},

	//confirm
	doConfirm:function (msg,frameName, callback) {
	     mDialogCallback = callback;
	     mFrameName = frameName;
	     $("#confirmInfo").html(msg);
	     $('#confirmModal').modal('show');
	 },
	 
	 //显示导出窗口
	 doExportModal:function (msg,iFrameName,callback){
		      mFrameName = iFrameName;
		      mDialogCallback = callback;
		    $("#exportTitle").html(msg);
			$("#exportModal").modal('show');
			
		},
	 onCallBack:function (mFrameName,mDialogCallback){
			if ("" == mFrameName){
				eval("("+mDialogCallback+")");	
			}else{
				var funStr = "window.frames['"+mFrameName+"']."+mDialogCallback;
				eval("("+funStr+")");	
			}
	 }
};
nightDriving2To5.init();
